<template>
  <div id="LabTMLBDict">
    <Breadcrumb content="批次输入" v-if="showBreadCrumbTag === true" />
    <GoBack :content="'批次输入'" v-if="showBreadCrumbTag === false" @closeDrawer="closeDrawer" :backUrl="url"></GoBack>
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="20">
          <el-scrollbar style="height: 100%">
            <div style="width:95%;">
              <el-form ref="formRef" :model="formData" label-width="80px" inline-message>
                <el-form-item label="工作组" prop="wtId">
                  <SelectWorkGroup style="width:100%;" ref="selectWorkGroupRef" :url="'/api/rptGroup/findRptGroup'" :inputWidth="'100%'" @getSelectedId="getSelectedId">
                  </SelectWorkGroup>
                </el-form-item>
                <el-form-item label="标本号" prop="sampleNo">
                  <el-input v-model="formData.sampleNo" placeholder="请输入1,2,5-8等格式" clearable @keyup.enter.native="selectWtIdChange"></el-input>
                </el-form-item>
                <el-form-item label="标本日期" prop="scheduleDate">
                  <el-date-picker style="width:100%;" v-model="formData.scheduleDate" :popper-style="{ zIndex: 9999999 }" :tabindex="999000" type="date" placeholder="选择标本日期" @change="selectWtIdChange" clearable />
                </el-form-item>
                <el-form-item label="病人类型" prop="visitTypeIds">
                  <el-checkbox-group style="width:100%;" v-model="formData.visitTypeIds" @change="(items) => checkedChange(items, 'visitTypeIds')">
                    <el-checkbox style="width:100%;" v-for="(item, index) in visitTypeList" :label="item.code" :key="index" border>
                      {{ item.name }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="样本类型" prop="specTypeIds">
                  <el-select style="width:100%" v-model="formData.specTypeIds" multiple collapse-tags filterable @change="(items) => checkedChange(items, 'specTypeIds')" placeholder="请选择">
                    <el-option v-for="item in specTypeList" :key="item.id" :label="item.sampleTypeName" :value="item.sampleTypeCode">
                    </el-option>
                  </el-select>
                </el-form-item>
                <!-- <el-form-item label="审核标志" prop="isReviewed">
                  <el-radio-group v-model="formData.isReviewed" style="width:100%;">
                    <el-radio-button :label="null">全部</el-radio-button>
                    <el-radio-button :label="2">已审核</el-radio-button>
                    <el-radio-button :label="0">未审核</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="打印标志" prop="isPrinted">
                  <el-radio-group v-model="formData.isPrinted" style="width:100%;">
                    <el-radio-button :label="null">全部</el-radio-button>
                    <el-radio-button :label="1">已打印</el-radio-button>
                    <el-radio-button :label="0">未打印</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="筛选条件">
                  <el-checkbox-group v-model="formData.processItem" @change="(items) => checkedChange(items, 'processItem', true)">
                    <el-checkbox style="width:100%;" label="isFilterNoResult" border>不处理无检验结果样本 </el-checkbox>
                    <el-checkbox style="width:100%;" label="isFilterNoSpecCode" border>不处理无条码号样本 </el-checkbox>
                    <el-checkbox style="width:100%;" label="isFilterNoPatName" border>不处理无病人姓名样本
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="selectWtIdChange">查询</el-button>
                  <el-button type="default" @click="resetForm">重置</el-button>
                </el-form-item> -->
              </el-form>
            </div>
            <vxe-toolbar class-name="margin-top bg-gray text-bold text-lg">
              <template #buttons>
                <span>请选择批次输入的模板</span>
              </template>
            </vxe-toolbar>
            <div>
              <vxe-table border="inner" ref="resultTemplateTable" resizable show-overflow height="200" :data="resultTemplateList" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{ isArrow: true }" @checkbox-change="selectTemplate" @checkbox-all="selectAllTemplate" :loading="teloading">
                <vxe-column type="checkbox" width="26" fixed="left"></vxe-column>
                <vxe-column field="templateName" title="模板名称" min-width="80" fixed="left"></vxe-column>
              </vxe-table>
            </div>
            <div>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="addItemDetail()"></vxe-button>
              <vxe-table ref="itemDetailTable" border resizable show-overflow :data="itemDetailList" :row-config="{ isCurrent: true, isHover: true }" @checkbox-change="selectItem" @checkbox-all="selectAllItem" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }">
                <vxe-column type="checkbox" width="22" fixed="left"></vxe-column>

                <vxe-column field="itemNa" title="模板项目" min-width="140" :edit-render="{ }">
                  <template #default="{ row }">
                    <span>{{ row.itemNa }}</span>
                  </template>
                  <template #edit="{ rowIndex }">
                    <SelectDataGrid :url="'/lab/rptResult/findRptResultItem'" :column="[
                      { field: 'itemNo', title: '编码' },
                      { field: 'itemNa', title: '名称' }
                    ]" :searchParam="{ rptGroup: formData.wtId }" :isPage="false" @SelectCellClick="
                      (e) => {
                        SelectRowClick(e, rowIndex);
                      }
                    " :showField="'itemNa'">
                    </SelectDataGrid>
                  </template>
                </vxe-column>
                <vxe-column field="rptResult" title="结果" width="120">
                  <template #default="{ row }">
                    <vxe-input v-model="row.rptResult"></vxe-input>
                  </template>
                </vxe-column>
              </vxe-table>
            </div>
          </el-scrollbar>

          <!-- 中间表格+右侧表格组件  -->
        </Pane>
        <pane size="80">
          <RptResultBatchInput ref="RptResultBatchInputRef"  :itemDetailList="itemDetailList" @search="selectWtIdChange" />
        </pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import GoBack from '@/components/GoBack.vue'; //返回组件
import { Splitpanes, Pane } from 'splitpanes';
import { reactive, ref, getCurrentInstance, onMounted, watch } from 'vue';
import { IsEmpty, formatDateTime } from '@/utils/common.ts';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import SelectWorkGroup from '../lab_bus/components/SelectWorkGroup.vue'; //工作组引入下拉组件
import RptResultBatchInput from './RptResultBatchInput.vue'; //中间表格+右侧表格组件
import { GetRptGroupOptions } from '@/utils/SysOptionsHelper';
import SelectItemGrid from '../lab_bus/components/SelectItemGrid.vue';
import SelectDataGrid from '@/components/SelectDataGrid.vue';
// 全局变量定义区 ==========
defineExpose({
  init
});

onMounted(() => {
  getDictPatTypeList();
  getSampleType();
});

let showBreadCrumbTag = ref(true); //当为true时显示的是普通面包屑 false显示的是返回组件
let url = ref(''); //抽屉要返回的路由地址

function init(row: any, row2: any) {
  url.value = row;
  showBreadCrumbTag.value = !row2;
}

// 关闭抽屉
function closeDrawer() {
  showBreadCrumbTag.value = true; //恢复成面包屑
  proxy.$emit('closeDrawer');
}

let { proxy }: any = getCurrentInstance();
let selectWorkGroupRef = ref(null);
const formRef = ref(); //表单ref标记
//病人类型
const visitTypeList: any[] = reactive([]);
//样本类型
const specTypeList = reactive([]);
let teloading = ref(false);
let resultTemplateList: any = reactive([]);
let itemDetailList: any = reactive([]);
let currentItemList: any = reactive([]);
// 表单绑定的数据类型限制
interface FormDataVO {
  sampleNo: string /*标本号*/;
  isFilterNoPatName: boolean /*无病人姓名样本*/;
  isFilterNoResult: boolean /*无检验结果样本*/;
  isFilterNoSpecCode: boolean /*无条码号样本*/;
  isPrinted: Number /*审核标志*/;
  isReviewed: Number /*打印标志*/;
  skipCount: Number /*样本类型最小数*/;
  maxResultCount: Number /*样本类型最大数*/;
  scheduleDate: string /*标本日期开始时间*/;
  specTypeIds: [] /*样本类型*/;
  visitTypeIds: [] /*病人类型*/;
  wtId: string /*工作组id*/;
  processItem: [];
}
// 表单绑定的数据
let formData = reactive<FormDataVO>({
  sampleNo: '',
  isFilterNoPatName: false,
  isFilterNoResult: false,
  isFilterNoSpecCode: false,
  isPrinted: null,
  isReviewed: null,
  maxResultCount: 0,
  scheduleDate: formatDateTime(new Date(), 'yyyy-MM-dd'),
  skipCount: 0,
  specTypeIds: [],
  visitTypeIds: [],
  wtId: '',
  processItem: []
});
let RptResultBatchInputRef = ref(null); //引用中间表格+右侧表格组件ref

// 方法定义区 =============
onMounted(() => {
  getSelectedId; // 接收子组件传过来的选中的id(选择的那个工作组的id)
});

function addItemDetail() {
  if (IsEmpty(formData.wtId)) {
    VxeMessage('请选择报告单元', VxeNotifyType.error);
    return;
  }
  const newRec = {
    itemNo: '',
    itemNa: '',
    testResult: '',
    type: '1'
  } as any;
  // push新的内容
  itemDetailList.push(newRec);
}
// 组件
//点击选择的那一项受检单位
function SelectRowClick(row, index) {
  const idx = itemDetailList.findIndex((item) => {
    return item.itemNo === row.itemNo;
  });

  if (idx > -1) {
    // this.handleResultRowClick(this.workResultList[idx]);
    VxeMessage('此检验项目已存在', VxeNotifyType.error);
    return;
  }
  itemDetailList[index].itemNo = row.itemNo;
  itemDetailList[index].itemNa = row.itemNa;
  proxy.$nextTick(() => {
    // 默认全选
    (proxy.$refs.itemDetailTable as any).setAllCheckboxRow(true);
  });
}

// 接收子组件传过来的选中的id(选择的那个工作组的id)
function getSelectedId(propValue: any) {
  GetRptGroupOptions(propValue.value);
  formData.wtId = propValue.value;
  RptResultBatchInputRef.value?.getWklt(formData);
  getResultTemplateList();
}

// 多选框绑定值变化
function checkedChange(items, name, isChange) {
  formData[name] = items;
  processItemChange(isChange);
}

// 筛选条件过滤
function processItemChange(isChange) {
  if (!isChange) {
    return;
  }
  if (formData.processItem.length > 0) {
    formData.processItem.forEach((item) => {
      formData[item] = true;
    });
  } else {
    formData.isFilterNoPatName = false;
    formData.isFilterNoResult = false;
    formData.isFilterNoSpecCode = false;
  }
}

// 重置表单
function resetForm() {
  formData.sampleNo = '';
  formData.isFilterNoPatName = false;
  formData.isFilterNoResult = false;
  formData.isFilterNoSpecCode = false;
  formData.isPrinted = null;
  formData.isReviewed = null;
  formData.maxResultCount = 0;
  formData.scheduleDate = '';
  formData.skipCount = 0;
  formData.specTypeIds = [];
  formData.visitTypeIds = [];
  formData.wtId = '';
  formData.processItem = [];
  selectWorkGroupRef.value?.resetSelectedVal(); //重置选中的工作组
}

//获取病人类型数据字典
function getDictPatTypeList() {
  visitTypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'PATTYPE' } })
    .then((res: any) => {
      //patTypeList.push(...res.data);
      Object.assign(visitTypeList, res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
//获取样本类型
function getSampleType() {
  specTypeList.length = 0;
  const url = '/api/lab/labSampleType/findSampleTypeList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      //patTypeList.push(...res.data);
      Object.assign(specTypeList, res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function getResultTemplateList() {
  if (IsEmpty(formData.wtId)) {
    VxeMessage('请选择报告单元', VxeNotifyType.error);
  } else {
    teloading.value = true;
    resultTemplateList.length = 0; //放入数据前清空数据
    const url = '/lab/template/getTemplateAndDetailByRptGroup';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { rptGroup: formData.wtId }
      })
      .then((res: any) => {
        resultTemplateList.push(...res.data);
        itemDetailList.length = 0;
        currentItemList.length = 0;
        teloading.value = false;
      })
      .catch((err: any) => {
        teloading.value = false;
        VxeMessage('获取获取当前字典的字段列表失败', VxeNotifyType.error);
      });
  }
}

function selectTemplate({ checked, row }) {
  currentItemList.length = 0;
  const filteredItems = itemDetailList.filter((item) => item.type === '1');
  itemDetailList.length=0;
  itemDetailList.push(...filteredItems);
  const recordList = (proxy.$refs.resultTemplateTable as any).getCheckboxRecords(true);
  if (recordList.length === 0) {
    return;
  }
  recordList.forEach((record) => {
    record.detailList.forEach((data) => {
      const index = itemDetailList.findIndex((item) => {
        return item.itemNo === data.itemNo; //判断模板项目是否已存在
      });
      if (index > -1) {
        itemDetailList[index] = data; //存在则替换
      } else {
        itemDetailList.push(data);
      }
    });
  });

  itemDetailList.forEach((item) => {
    currentItemList.push(item);
  });
  proxy.$nextTick(() => {
    // 默认全选
    (proxy.$refs.itemDetailTable as any).setAllCheckboxRow(true);
  });
}
function selectAllTemplate({ checked }) {
  currentItemList.length = 0;
  const filteredItems = itemDetailList.filter((item) => item.type === '1');
  itemDetailList.length=0;
  itemDetailList.push(...filteredItems);
  if (checked) {
    resultTemplateList.forEach((record) => {
      record.detailList.forEach((data) => {
        const index = itemDetailList.findIndex((item) => {
          return item.itemNo === data.itemNo; //判断模板项目是否已存在
        });
        if (index > -1) {
          itemDetailList[index] = data; //存在则替换
        } else {
          itemDetailList.push(data);
        }
      });
    });
    itemDetailList.forEach((item) => {
      currentItemList.push(item);
    });
    proxy.$nextTick(() => {
      // 默认全选
      (proxy.$refs.itemDetailTable as any).setAllCheckboxRow(true);
    });
  }
}

function selectItem({ checked, row }) {
  const rowIdx = currentItemList.findIndex((item) => {
    return item.id === row.id;
  });
  if (checked && rowIdx === -1) {
    currentItemList.push(row);
  } else if (!checked && rowIdx !== -1) {
    currentItemList.splice(rowIdx, 1);
  }
}
function selectAllItem({ checked }) {
  currentItemList = [];
  if (checked) {
    itemDetailList.forEach((item) => {
      currentItemList.push(item);
    });
  }
}

function selectWtIdChange() {
  RptResultBatchInputRef.value?.getWklt(formData);
  getResultTemplateList();
}
</script>
<style lang="scss" scoped>
#LabTMLBDict {
  width: 100%;
  height: 100%;

  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;
      height: 100%;

      :deep(.el-scrollbar__view) {
        height: 100%;

        .el-form {
          height: 100%;
          padding-top: 15px;
          box-sizing: border-box;

          .el-checkbox {
            margin: 8px 10px 0 0;
          }
        }
      }
    }
  }
}
</style>
